﻿using System;
using System.Linq;
using System.Data.Common;
using System.Collections.Generic;
using MicroDb.Options;
using Newtonsoft.Json.Linq;
using Npgsql;
using NpgsqlTypes;
using MicroDb.Basis;

namespace MicroDb.PostgreSql
{
    public class NpgSqlExecute : SqlExecute
    {
        private readonly string connectionString;
        public NpgSqlExecute(MicroDbOptions microDb)
        {
            this.connectionString = microDb.DbConnectionString;
        }

        protected override DbConnection CreateDbConnection()
        {
            return new Npgsql.NpgsqlConnection(connectionString);
        }

        protected override DbParameter[] CreateParameters(IDictionary<string, object> parameters)
        {
            return parameters.Select(a =>
            {
                var pa = new NpgsqlParameter(a.Key, a.Value ?? DBNull.Value);
                if (a.Value is JToken j)
                {
                    pa.Value = j.ToString(Newtonsoft.Json.Formatting.None);
                    pa.NpgsqlDbType = NpgsqlDbType.Json;
                }
                return pa;
            }).ToArray();
        }
    }
}
